<template>
  <div >
    <el-tree
      :data="treeData"
      :props="defaultProps"
      highlight-current
      node-key="id"
      default-expand-all
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
        
        
          <span style="margin-left: 8px">{{ data.name }}</span>
          <span v-if="!data.children || data.children.length === 0" class="no-children"></span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { getDeptTree } from '@/api/system/dept';

// 定义树节点类型
interface TreeNode {
  id: string;
  name: string;
  pid: string | null;
  children: TreeNode[];
  [key: string]: any;
}

// 树形数据
const treeData = ref<TreeNode[]>([]);

// 树形组件配置
const defaultProps = {
  children: 'children',
  label: 'name'
};

// 获取部门树数据
const fetchDeptTree = async () => {
  try {
    const rawData = await getDeptTree();
    // 转换数据格式（将Children转为children）
    const formattedData = transformTreeData(rawData.Data);
    treeData.value = formattedData;
  } catch (error) {
    console.error('获取部门树失败：', error);
  }
};

// 递归转换树形数据格式
const transformTreeData = (data: any[]): TreeNode[] => {
  return data.map(item => {
    return {
      id: item.Id,                  // 唯一标识
      name: item.Name,              // 显示名称
      pid: item.ParentId,           // 父级ID
      children: item.Children ? transformTreeData(item.Children) : [], // 递归处理子节点
      ...item                      // 保留其他原始字段
    };
  });
};

// 节点点击事件
const handleNodeClick = (data: TreeNode) => {
  console.log('选中部门：', data);
  // 可在此触发查看部门详情等操作
};

// 初始化加载数据
onMounted(() => {
  fetchDeptTree();
});
</script>

<style scoped>
.dept-tree-container {
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
  height: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 自定义节点样式 */
.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 6px 0;
}

/* 无子部门标识 */
.no-children {
  color: #c0c4cc;
  margin-left: 10px;
  font-size: 12px;
}

:deep(.el-tree-node__content) {
  height: 36px;
}
</style>